import React, { useEffect, useState, useCallback } from 'react'
import { Anchor } from 'antd'
import event from '@/utils/event'
import style from './index.module.scss'
const { Link } = Anchor

export default function Catalog() {
  const [tocArray, setTocArray] = useState<tocArrayType>([])
  const [activeCurrent, setActiveCurrent] = useState(0)
  const [domPositionTop, setDomPositionTop] = useState<number[]>([])
  const [detailDom, setDetailDom] = useState<Element | null>(null)
  const detailScroll = useCallback(
    (e: Event) => {
      if (!e.target) return
      const domScrollTop = (e.target as HTMLDivElement).scrollTop
      for (let i = domPositionTop.length - 1; i >= 0; i--) {
        if (domScrollTop >= domPositionTop[i]) {
          setActiveCurrent(i)
          break
        }
      }
    },
    [domPositionTop]
  )

  useEffect(() => {
    event.on('blogContent', (tocArrays: tocArrayType, tops: number[]) => {
      setDetailDom(document.querySelector('#detail'))
      setDomPositionTop(tops)
      setTocArray(tocArrays)
    })

    event.on('destroyDetai', () => {
      setDetailDom(null)
      setTocArray([])
      setActiveCurrent(0)
    })
  }, [detailScroll])
  useEffect(() => {
    if (tocArray.length === 0 || detailDom === null) return
    detailDom?.addEventListener('scroll', detailScroll)
  }, [tocArray, detailScroll, detailDom])
  return (
    <div className={style.catalog}>
      {detailDom && (
        <Anchor
          affix={false}
          bounds={0}
          showInkInFixed={true}
          getCurrentAnchor={() => `#${tocArray[activeCurrent]?.anchor}`}
          getContainer={() => detailDom as HTMLDivElement}
          targetOffset={20}
          className={style.anchor}
          onClick={function (e) {
            e.preventDefault()
          }}
        >
          {tocArray.map((el, i) => {
            return (
              <Link
                key={i}
                href={`#${el.anchor}`}
                title={el.content}
                className={`${style.link} ${style['link_' + (el.level - 1)]}`}
              ></Link>
            )
          })}
        </Anchor>
      )}
    </div>
  )
}
